<template>
  <div class="flex h-100%" :class="{ 'flex-border': props.rightShow }">
    <div class="tree1 h-100% flex-d-col w-260px">
      <el-input
        v-if="treeFilterInput"
        v-model="filterText"
        class="w-100%"
        placeholder="请输入关键词"
        :prefix-icon="Search"
        clearable
      />

      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="defaultProps"
        default-expand-all
        :filter-node-method="filterNode"
        node-key="id"
        :highlight-current="true"
        @current-change="handleNodeClick"
        class="of-overlay"
        :expand-on-click-node="false"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node flex-y-center">
            <!-- <el-icon class="mr-10px border" v-if="data.children.length && !node.expanded"
              ><Plus
            /></el-icon>
            <el-icon class="mr-10px border" v-if="data.children.length && node.expanded"
              ><Minus
            /></el-icon>
            <el-icon
              class="mr-10px border"
              style="visibility: hidden"
              v-if="!data.children.length"
              ><Minus
            /></el-icon> -->
            <el-icon v-if="data.children.length && node.expanded"
              ><FolderOpened
            /></el-icon>
            <el-icon v-else><Folder /></el-icon>
            <span class="ml-10px">{{ node.label }}</span>
          </span>
        </template>
      </el-tree>
    </div>
    <div v-if="props.rightShow" class="tree2 flex-d-col min-w-240px">
      <el-input
        v-model="filterQuestion"
        style="width: 240px"
        class="mt-16px ml-20px mr-20px mb-6px"
        placeholder="请输入题库关键词"
        :prefix-icon="Search"
        clearable
      />
      <el-button
        v-if="props.addBtnShow && acTree.id && acTree.id != 'all'"
        type="primary"
        plain
        class="outline mt-6px ml-20px mr-20px mb-6px"
        style="width: 240px"
        @click="add"
      >
        <template #icon>
          <el-icon>
            <Plus />
          </el-icon>
        </template>
        新增题库
      </el-button>
      <ul v-if="CpuQuestionList.length > 0" class="of-y-overlay mb-10px mt-10px">
        <li
          v-for="i in CpuQuestionList"
          class="flex-y-center cursor-pointer"
          @click="
            () => {
              if (String(i.id).indexOf('new') == 0) return;
              acQuestion = i;
            }
          "
          :class="{ ac: acQuestion?.id == i.id }"
        >
          <el-icon class="mr-6px"><List /></el-icon>
          <template v-if="String(i.id).indexOf('new') == 0">
            <el-input
              ref="refInput"
              v-model="i.questionBank"
              placeholder="输入题库名称"
              @blur="addQuestion(i)"
            ></el-input>
          </template>
          <span v-else>{{ i.questionBank }}</span>
        </li>
      </ul>
      <el-empty v-else description="暂无数据" image-size="60" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search } from "@element-plus/icons-vue";
import { ref, computed } from "vue";
import {
  ApiGetQuestionBank,
  ApiPostQuestionBank,
  ApiGetOrganizationTree,
} from "@/api/resource-management/theory";
import { ElTree } from "element-plus";

const props = defineProps({
  treeFilterInput: {
    type: Boolean,
    default: true,
  },
  // 右侧题库列表显示
  rightShow: {
    type: Boolean,
    default: false,
  },
  // 右侧题库列表上的新增按钮显示
  addBtnShow: {
    type: Boolean,
    default: false,
  },
});

// acTreeData:选中组织， acQuestionData:选中题库
const emits = defineEmits(["acTreeData", "acQuestionData"]);

interface Tree {
  id: string;
  code: string;
  displayName: string;
  children?: Tree[];
  [propName: string]: any;
}

const gParams = {
  stationName: null,
  trainDepotName: null,
  railwayBureau: null,
};

const treeData = ref<Tree[]>([
  {
    id: "all",
    displayName: "全部",
    children: [],
  },
]); // 组织
const acTree = ref({ id: "" }); // 选中的组织数据
const questionList = ref([]); // 题库列表
const CpuQuestionList = computed(() => {
  return questionList.value.filter(
    (e) =>
      e.questionBank.includes(filterQuestion.value) || String(e.id).indexOf("new") > -1
  );
});
const acQuestion = ref<{ id: string } | null>(null); // 初始化为包含 id 属性的对象或 null
const defaultProps = {
  children: "children",
  label: "displayName",
};
const filterText = ref("");
const treeRef = ref<InstanceType<typeof ElTree>>();
watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.displayName.includes(value);
};
const handleNodeClick = (data: Tree) => {
  // console.log(getParent(treeData.value, data.id), 99);
  acQuestion.value = "";
  acTree.value = data;
  let obj = {};
  getParent(treeData.value, acTree.value.id).map((e) => {
    obj[e.field] = e.value;
  });
  emits("acTreeData", data, obj); // 选中组织数据
  if (props.rightShow) {
    getQuestionBank(obj);
  }
};
// 树结构获取所有父级
const getParent = (list, id) => {
  for (let i in list) {
    if (list[i].id == id) {
      return [list[i]];
    }
    if (list[i].children) {
      let node = getParent(list[i].children, id);
      if (node !== undefined) {
        return node.concat(list[i]);
      }
    }
  }
};

const getQuestionBank = (data) => {
  let params = {
    ...gParams,
    ...data,
  };
  ApiGetQuestionBank({ ...params }).then((res) => {
    if (res.code == 200) {
      questionList.value = res.data;
    }
  });
};
watchEffect(() => {
  let obj = {};
  getParent(treeData.value, acTree.value.id)?.map((e) => {
    obj[e.field] = e.value;
  });
  emits("acQuestionData", acQuestion.value, { ...gParams, ...obj });
});

onBeforeMount(() => {
  ApiGetOrganizationTree().then((res) => {
    if (res.code == 200) {
      res.data = [res.data];
      treeData.value = [
        ...treeData.value,
        ...res.data.map((e) => {
          return {
            displayName: e.description,
            id: e.description,
            field: "railwayBureau",
            value: e.value,
            children: e.children.map((el) => {
              return {
                displayName: el.description,
                id: el.description,
                field: "trainDepotName",
                value: el.value,
                children: el.children.map((ell) => {
                  return {
                    displayName: ell.description,
                    id: ell.description,
                    field: "stationName",
                    value: ell.value,
                    children: [],
                  };
                }),
              };
            }),
          };
        }),
      ];
    }
  });
});

const refInput = ref(null);
const add = () => {
  if (questionList.value.some((e) => e.id.indexOf("new") > -1)) {
    return;
  }
  let index = questionList.value.length;
  questionList.value.push({ id: "new-" + index, questionBank: "", order: index + 1 });
  nextTick(() => {
    refInput.value.focus();
  });
};
const addQuestion = (data) => {
  if (!data.questionBank) {
    return;
  }
  let params = {
    questionBank: data.questionBank,
  };
  getParent(treeData.value, acTree.value.id).map((e) => {
    params[e.field] = e.value;
  });
  ApiPostQuestionBank({ ...gParams, ...params }).then((res) => {
    if (res.code == 200) {
      ElMessage.success("题库添加成功！");
      getQuestionBank({
        stationName: params.stationName,
        trainDepotName: params.trainDepotName,
        railwayBureau: params.railwayBureau,
      });
    }
  });
};

const filterQuestion = ref("");
</script>

<style scoped lang="scss">
.border {
  border: 1px solid;
  border-radius: 2px;
}
.flex {
  background: linear-gradient(180deg, #ffffff 0%, rgba(255, 255, 255, 0.8) 100%);
  border-radius: 20px 20px 20px 20px;
  overflow: hidden;
  width: fit-content;
  &-border {
    border: 1px solid rgba(7, 113, 255, 0.4);
  }
}
.tree1 {
  background: linear-gradient(180deg, #60a5ff 0%, #2a7aeb 100%);
  border-radius: 20px 20px 20px 20px;
  padding: 16px 12px;
  ::v-deep .el-tree {
    margin-top: 20px;
    background: transparent;
    color: #fff;
    &-node {
      &__content {
        border-radius: 6px;
        &:hover {
          background-color: #67a8ff;
        }
      }
      &__expand-icon {
        // display: none;
        color: white;
      }
      &:focus {
        & > .el-tree {
          &-node {
            &__content {
              background-color: transparent;
            }
          }
        }
      }
    }
    &--highlight-current {
      .el-tree-node.is-current > .el-tree-node__content {
        background-color: var(--el-color-primary-light-3);
      }
    }
    &__empty-text {
      color: #fff;
    }
  }
}
.tree2 {
  ul {
    li {
      padding: 10px 20px;
      &:hover,
      &.ac {
        background: linear-gradient(
          90deg,
          var(--el-color-primary) 0%,
          var(--el-color-primary-light-3) 100%
        );
        color: #fff;
      }
    }
  }
}
</style>
